<?php

class ParticipantController extends Zend_Controller_Action 
{
    protected $_model;
	protected $user;
	public function preDispatch(){
		if (Zend_Auth::getInstance()->hasIdentity()) {
			$this->user = Zend_Auth::getInstance()->getIdentity();
		}else{
			if ('register' != $this->getRequest()->getActionName() &&
                'confirm' != $this->getRequest()->getActionName() &&
                'forgot' != $this->getRequest()->getActionName() &&
                'recover' != $this->getRequest()->getActionName() &&
                'edit' != $this->getRequest()->getActionName()) {
                $this->_forward('index', 'login');
            }
		}
	}
	public function init()
    {
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('view', 'html')
                    ->addActionContext('comment', 'html')                    
                    ->initContext();
    }
    public function indexAction(){
    		
    }
    public function viewallAction()
    {    		
        $model = $this->_getModel();
        $this->view->participants = $model->fetchEntries();   
    }
    public function allAction()
    {
    	$request = $this->getRequest();
    	$callback = $request->getParam('callback');
        $model = $this->_getModel();
		$sort = $request->getParam('sort');
		$dir = $request->getParam('dir');
        $start = $request->getParam('start');
        $limit = $request->getParam('limit');
        $filter = $request->getParam('filter');
     	$count = $total = $model->getTotalFilter($filter);        
        $participants = $model->getParticipantsFilter($sort, $dir, $start, $limit, $filter);
        $json = array();
        $json['totalCount'] = $count;
        $json['participants'] = $participants;
        echo $callback.'('.Zend_Json::encode($json).')';
        die();
    }
 	public function getAction(){
		$request = $this->getRequest();
    	$callback = $request->getParam('callback');
        $model = $this->_getModel();
		$json = array();
		$p = array();
        $p[0] = $model->fetchEntry($this->user->id)->toArray();
		$json['totalCount'] = "1";
		$json['p'] = $p;
        echo $callback.'('.Zend_Json::encode($json).')';
        die();
	}
	public function profileAction(){
        $this->view->navTitle = $this->view->translate('profile');
	}
    public function forgotAction(){
        $this->view->navTitle = $this->view->translate('forgot');
	}
    public function recoverAction(){
        $request = $this->getRequest();
    	if($request->isPost()){
			$email = $request->getParam('email');    		
            $user = $this->_getModel()->getByEmail($email);
            if(!isset($user)){
				$json = array();
				$json['success'] = false;					
				$error = array();					
				$error['email'] = 'No such user!';					
				$json['errors'] = $error;
				echo Zend_Json::encode($json);
				die();
			}
            $pass = $this->createRandomPassword(6);
            $user->password = md5($pass);
			$user->save();
			$this->recoverMail($pass, $email);
		}
        die();
	}
   function createRandomPassword($len) {
        $chars = "abcdefghijkmnopqrstuvwxyz023456789";
        srand((double)microtime()*1000000);
        $i = 0;
        $pass = '' ;

        while ($i <= $len) {
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $pass = $pass . $tmp;
            $i++;
        }
        return $pass;
    }

	public function editAction()
    {
		$request = $this->getRequest();
    	if($request->isPost()){
			$data = $request->getParams();
    		$pass = $request->getParam('old_pass');
			if(isset($pass) && $pass != ''){
				$exist = $this->_getModel()->checkPass($pass, $this->user->id); 
				if(!$exist){
					$json = array();
					$json['success'] = false;					
					$error = array();					
					$error['old_pass'] = 'Invalid current password.';					
					$json['errors'] = $error;
					echo Zend_Json::encode($json);
					die();
				}
				$data['password'] = md5($data['password']);
			}else{
				unset($data['password']);
			}				
			$model = $this->_getModel();			
			$data['id'] = $this->user->id;
			$id = $model->save($data);
			die();
		}
    }		
    public function setreviewersAction(){
        $request = $this->getRequest();
		if($request->isPost()){
			$list = explode(':', $request->getParam('rList'));			
			$p = $this->_getModel();
			$p->setReviewers($list);			
			die();	
		}	
    }
    public function activateAction(){
        $request = $this->getRequest();
		if($request->isPost()){
			$list = explode(':', $request->getParam('rList'));			
			$p = $this->_getModel();
			$p->setActivated($list);			
			die();	
		}	
    }
    public function registerAction()
    {
        $this->view->navTitle = $this->view->translate('register');
    	$request = $this->getRequest();
    	if($request->isPost()){
    		$email = $request->getParam('email');
    		$duplicate = $this->_getModel()->checkEmail($email);
			if($duplicate){
				$json = array();
				$json['success'] = false;					
				$error = array();					
				$error['email'] = 'Duplicate email address.';					
				$json['errors'] = $error;
				echo Zend_Json::encode($json);
				die();
			}				
			$model = $this->_getModel();
        	$data = $request->getParams();
        	$data['isReviewer'] = 0;
        	$stamp = time();
        	$data['stamp'] = $stamp;
        	$id = $model->save($data);
        	$this->confirmationMail($id, $stamp, $data['first_name'], $data['last_name'], $data['email']);
        	die();
		}		
    }
    
	public function confirmAction(){
        $this->view->navTitle = $this->view->translate('confirm');
		$request = $this->getRequest();
		if($request->isGet()){
			$id = $request->getParam('id');
			$stamp = $request->getParam('st');
			$model = $this->_getModel();
			if(is_numeric($id) && is_numeric($stamp)){
				$ok = $model->confirmRegistration($id, $stamp);
				if($ok){
					$this->view->message = $this->view->translate('confirm_msg');
				}else{
					$this->view->message = "No such user!";
				}
			}else{
				$this->view->message = "Invalid request for activation.";
			}
		}
	}
  
    protected function _getModel()
    {
        if (null === $this->_model) {
            require_once APPLICATION_PATH . '/models/Participant.php';
            $this->_model = new Model_Participant();
        }
        return $this->_model;
    }
		private function getAreas(){
				require_once APPLICATION_PATH . '/models/Area.php';
      	$model = new Model_Area();
      	return $model->fetchEntries();
    } 
    private function getSelectItems(){
        $data = $this->getAreas();        
        $size = count($data);
        $areas = array();                
        for($i = 0; $i < $size; $i++){
        	$areas[$data[$i]['id']] = $data[$i]['name'];
        }
        return $areas;
    }
    
    protected function confirmationMail($id, $stamp, $first_name, $last_name, $email){
    	$subject = 'ETAI - Confirm Registration';
        $c = $this->getActiveConference();
        $conference = $c->name_en;
        
        $link_mk = $this->view->url(array('language' => 'mk', 'controller'=>'participant', 'action' => 'confirm'), 'default', true);
    	$link_mk .='/?id=' . $id . '&st=' . $stamp;
        $message = '<p>Почитувани <b>' . $first_name . " " . $last_name . '</b></p>
                    <p>Ви благодариме за вашата регистрација на <b>' . $conference . '</b></p>
					<p>Ве молиме кликнете на следниот линк за да ја комплетирате Вашата регистрација.</p>
					<p>Линк: <a href="' . SERVER_HOST . $link_mk . '">' . SERVER_HOST . $link_mk . '</a></p>
                    <p>Ако линкот не работи, ве молиме копирајте го во адресниот простор на вашиот веб прелистувач.<br/>
					Ако оваа регистрација не е Ваша, ве молиме игнорирајте ја оваа порака.</p>';
                    
        $message .= '<br/><br/><hr/><br/>';
        
        $link_en = $this->view->url(array('language' => 'en', 'controller'=>'participant', 'action' => 'confirm'), 'default', true);
    	$link_en .='/?id=' . $id . '&st=' . $stamp;
        $message .= '<p>Dear <b>' . $first_name . " " . $last_name . '</b></p>
                    <p>Thanks for Your registration on <b>' . $conference . '</b></p>
					<p>Please click the folowing link to complete Your registration.</p>
					<p>Link: <a href="' . SERVER_HOST . $link_en . '">' . SERVER_HOST . $link_en . '</a></p>
                    <p>If the link doesn\'t work, please copy it in the address bar on Your WEB Browser.<br/>
					If this registration is not for You, pleace disregard this message.</p>';
			
        $mail = new Zend_Mail('utf-8');
        $mail->setBodyHtml($message)
            ->setFrom('admin@etai.feit.ukim.edu.mk', 'ETAI - Paper Submition System')
            ->addTo($email, $first_name . ' ' . $last_name)
            ->setSubject($subject)
            ->send();
            
        /* uncomment if mail don't work*/
        $json = array();
        $json['success'] = true;					        
        $json['msg'] = '';
        echo Zend_Json::encode($json);
        /* */
    }
    function recoverMail($pass, $email){
        $subject = 'ETAI - Password Recover';
        
    	$message = '<p>Ова се вашите нови информации за најава</p><p>Е-Маил: <b>' . $email . '</b><br/>Лозинка: <b>' . $pass . '</b></p>';
        
        $message .= '<br/><br/><hr/><br/>';
        
        $message .= '<p>Here are your new login information</p><p>Email: <b>' . $email . '</b><br/>Password: <b>' . $pass . '</b></p>';
			
        $mail = new Zend_Mail('utf-8');
        $mail->setBodyHtml($message)
            ->setFrom('admin@etai.feit.ukim.edu.mk', 'ETAI - Paper Submition System')
            ->addTo($email)
            ->setSubject($subject)
            ->send();
    }    
    private function getActiveConference(){
		require_once APPLICATION_PATH . '/models/Conference.php';
      	$model = new Model_Conference();
      	return $model->getActive();
    }
    
    public function deletepAction(){
        $request = $this->getRequest();
        $id = $request->getParam('id');
        $p = $this->_getModel();
        $p->deleteParticipant($id);
        echo 'deleted';
        die();
    }
}
